<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-left">
        <el-input
          size="mini"
          v-model="searchKey"
          placeholder="请输入品牌名称搜索"
          style="width: 250px"
          class="filter-item"
          @keyup.enter.native="handleFilter"
          @input="handleFilter"
        />
        <!-- <el-button
          size="mini"
          v-waves
          class="filter-item"
          style="margin-left: 10px"
          type="primary"
          icon="el-icon-search"
          @click="handleFilter"
        >
          查询
        </el-button> -->
      </div>
      <div class="filter-right">
        <el-button icon="el-icon-plus" type="primary" size="mini" @click="handleAdd">
          新增品牌
        </el-button>
      </div>
    </div>
    <el-table
      :data="pageList"
      border
      stripe
      fit
      highlight-current-row
      v-loading="listLoading"
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="brand_name" label="品牌名称" align="center">
      </el-table-column>
      <el-table-column label="品牌Logo" align="center">
        <template slot-scope="{ row }">
          <img
            :src="row.brand_img"
            alt=""
            style="width: 50px; height: 50px"
            v-if="row.brand_img"
          />
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column prop="alarm_config" label="品牌钉钉通知配置" align="center">
      </el-table-column>
      <el-table-column label="创建时间" width="200px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.created_at | formate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" width="200px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.updated_at | formate }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <el-button @click="handleModify(scope.row)" type="text" size="small"
            >修改</el-button
          >
          <el-button
            @click="handleDelete(scope.row)"
            type="text"
            size="small"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getPageList"
    />

    <!-- 新增修改 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="550px">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="品牌名称" label-width="90px" prop="brandName">
          <el-input
            v-model="form.brandName"
            autocomplete="off"
            maxlength="50"
            placeholder="请输入品牌名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌Logo" label-width="90px">
          <el-input
            v-model="form.brandImg"
            autocomplete="off"
            placeholder="请输入品牌Logo地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌钉钉通知配置" label-width="90px" prop="alarmConfig">
          <vue-json-editor
            v-model="form.alarmConfig"
            :showBtns="false"
            :mode="'code'"
            lang="zh"
            :expandedOnStart="false"
            @json-change="onJsonSave"
            @json-save="onJsonSave"
            @has-error="onError"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getBrandsPage,
  insertBrands,
  updateBrands,
  deleteBrands,
} from "@/api/brand";
import { checkUserToken, getDataByCode } from "@/api/user";
import waves from "@/directive/waves"; // waves directive
import { curentTime } from "@/filters/index";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
// 导入模块
import vueJsonEditor from "vue-json-editor";
export default {
  name: "Brand",
  components: { Pagination, vueJsonEditor },
  directives: { waves },
  filters: {
    formate(date) {
      return curentTime(date);
    },
  },
  data() {
    return {
      // 品牌数据
      pageList: [],
      // 品牌总数
      total: 0,
      // 加载
      listLoading: true,
      // 查询条件
      listQuery: {
        pageNum: 1,
        pageSize: 10,
      },
      searchKey: "",
      //   控制弹窗
      dialogFormVisible: false,
      //   弹窗名称
      title: "",
      //   表单信息
      form: {
        brandName: "",
        brandImg: "",
        alarmConfig: null
      },
      // 表单检验
      rules: {
        brandName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
        ],
        alarmConfig: [
          { required: true, message: "请输入品牌钉钉通知配置", trigger: "blur" },
        ],
      },
      hasJsonFlag: true,
      dataGroupRobot: null
    };
  },
  async created() {
    this.getDingDingConfig();
    await this.getPageList();
  },
  methods: {
    getDingDingConfig(){
      // 获取配置数据
      getDataByCode({ code: "GroupRobot" }).then((res) => {
        this.dataGroupRobot = res.data.GroupRobot || null;
      });
    },
    httprequest(param) {
      //拷贝图片到表单数据之中
      this.form.file = param.file;
    },
    // 按需查询
    async handleFilter() {
      this.listQuery.searchKey = this.searchKey;
      this.listQuery.pageNum = 1;
      await this.getPageList();
    },

    // 查询列表
    async getPageList() {
      try {
        const res = await getBrandsPage(this.listQuery);
        this.total = res.data.total;
        this.pageList = res.data.lists;
        this.listLoading = false;
      } catch (error) {
        console.log(error);
      }
    },

    // 新增
    handleAdd() {
      checkUserToken().then((res) => {
        if (res.data) {
          this.title = "新增品牌";
          this.$delete(this.form, "id");
          this.dialogFormVisible = true;
          this.form.alarmConfig = this.dataGroupRobot;
        }
      });
    },

    // 修改
    handleModify(row) {
      this.title = "修改品牌";
      this.dialogFormVisible = true;
      this.form.id = row.id;
      this.form.brandName = row.brand_name;
      this.form.alarmConfig = row.alarm_config ? JSON.parse(row.alarm_config) : this.dataGroupRobot;
      this.form.brandImg = row.brand_img;
    },
    // 删除
    handleDelete(row) {
      this.$confirm("此操作将删除该品牌信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteBrands(row.id).then((res) => {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.getPageList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 提交表单信息
    async submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            updateBrands({
              id: this.form.id,
              brandImg: this.form.brandImg || "",
              brandName: this.form.brandName,
              alarmConfig: JSON.stringify(this.form.alarmConfig)
            }).then((res) => {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.getPageList();
              this.resetForm("form");
            });
          } else {
            insertBrands({
              brandImg: this.form.brandImg || "",
              brandName: this.form.brandName,
              alarmConfig: JSON.stringify(this.form.alarmConfig)
            }).then((res) => {
              this.$message({
                message: "新增成功",
                type: "success",
              });
              this.getPageList();
              this.resetForm("form");
            });
          }
        } else {
          return false;
        }
      });
    },

    // 取消
    resetForm(formName) {
      this.dialogFormVisible = false;
      this.$nextTick(() => {
        this.$refs[formName].resetFields();
      });
      if (this.form.brandName) {
        this.form.brandName = "";
      }
      if(this.form.alarmConfig){
        this.form.alarmConfig = "";
      }
      if (this.form.brandImg) {
        this.form.brandImg = "";
      }
    },
     // json编辑器回调方法
    onJsonSave(value) {
      this.form.alarmConfig = value;
      this.hasJsonFlag = true;
    },
    onError(value) {
      this.hasJsonFlag = false;
    },
    // hanchange(file) {
    //   //显示图片
    //   this.ruleForm.imageUrl = URL.createObjectURL(file.raw);
    // },
  },
};
</script>
  
  <style lang="scss">
.filter-container {
  display: flex;
  justify-content: space-between;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
    